import React, { useState } from 'react';
import { Form, Space, Button, Table } from 'antd';
import { keyBy } from 'lodash-es';
import ListQuery from './DialogListQuery';
import { useDeviceIds, useDeviceListColumns, useDeviceList } from '../../hooks';

/**
 * 根据模型字段获取设备类型枚举
 */
const getDeviceTypeOptions = (data) => {
    const { propertyEnumValue } = data.find(({ propertyKey }) => propertyKey === 'device_type_name') ?? {};

    try {
        return Object.entries(JSON.parse(propertyEnumValue)).map(([value, label]) => ({ value, label }));
    } catch (err) {
        return [];
    }
};

/**
 * 标签页内容
 */
function DialogTabContent(props) {
    const { modelId, modelName, selectedRows, onSelect } = props;

    const [deviceTypeOptions, setDeviceTypeOptions] = useState([]);

    const [form] = Form.useForm();
    const deviceIds = useDeviceIds();
    const deviceListColumns = useDeviceListColumns({
        defaultParams: [modelId],
        onDataSourceSuccess(data) {
            setDeviceTypeOptions(getDeviceTypeOptions(data));
        },
    });
    const deviceList = useDeviceList(modelId, { form });

    return (
        <Space style={{ display: 'flex' }} direction="vertical" size={10}>
            <ListQuery
                deviceTypeOptions={deviceTypeOptions}
                form={form}
                onQuery={() => {
                    deviceList.search.submit();
                }}
            />
            <Button
                type="primary"
                disabled={!deviceList.tableProps.pagination.total}
                loading={deviceIds.loading}
                onClick={async () => {
                    onSelect(
                        Object.values({
                            ...keyBy(selectedRows, 'resourceId'),
                            ...keyBy(
                                (
                                    await deviceIds.runAsync({
                                        ...deviceList.params[0],
                                        cmModuleId: modelId,
                                    })
                                ).map((resourceId) => ({
                                    moduleId: modelId,
                                    moduleName: modelName,
                                    resourceId,
                                })),
                                'resourceId'
                            ),
                        })
                    );
                }}
            >
                一键全选
            </Button>
            <Table
                rowKey="cm_unid"
                scroll={{ x: 'max-content' }}
                columns={deviceListColumns.data}
                rowSelection={{
                    selectedRowKeys: selectedRows.map(({ resourceId }) => resourceId),
                    onSelect(record, selected) {
                        if (selected) {
                            onSelect([
                                ...selectedRows,
                                { moduleId: modelId, moduleName: modelName, resourceId: record.cm_unid },
                            ]);
                        } else {
                            onSelect(selectedRows.filter(({ resourceId }) => resourceId !== record.cm_unid));
                        }
                    },
                    onSelectAll(selected, _, changedRows) {
                        if (selected) {
                            onSelect([
                                ...selectedRows,
                                ...changedRows.map(({ cm_unid }) => ({
                                    moduleId: modelId,
                                    moduleName: modelName,
                                    resourceId: cm_unid,
                                })),
                            ]);
                        } else {
                            const changedRowKeys = changedRows.map(({ cm_unid }) => cm_unid);
                            onSelect(
                                selectedRows.filter(({ resourceId }) => changedRowKeys.indexOf(resourceId) === -1)
                            );
                        }
                    },
                }}
                {...deviceList.tableProps}
                loading={deviceListColumns.loading || deviceList.tableProps.loading}
                pagination={{
                    showSizeChanger: true,
                    showTotal: (total) => `共 ${total} 条`,
                    ...deviceList.tableProps.pagination,
                }}
            />
        </Space>
    );
}

export default DialogTabContent;
